#include "sound.h"

static gboolean bus_call(GstBus *bus,GstMessage *msg,gpointer data)
{
    GMainLoop *loop = (GMainLoop *) data;//这个是主循环的指针，在接受EOS消息时退出循环
    switch (GST_MESSAGE_TYPE(msg)){
        case GST_MESSAGE_EOS:
            g_main_loop_quit(loop);
            break;
        case GST_MESSAGE_ERROR:
             g_main_loop_quit(loop);
             break;
        default:
             break;
    }
    return TRUE;
}
void * sound()
{
    GMainLoop *loop;
    GstElement *pipeline,*source,*decoder,*sink;//定义组件
    GstBus * bus;
    gst_init(NULL,NULL);
    loop = g_main_loop_new(NULL,FALSE);//创建主循环，在执行 g_main_loop_run后正式开始循环

    pipeline = gst_pipeline_new("audio-player");
    source = gst_element_factory_make("filesrc","file-source");
    decoder = gst_element_factory_make("mad","mad-decoder");
    sink = gst_element_factory_make("autoaudiosink","audio-output");
    g_object_set(G_OBJECT(source),"location","./sounds/msg.mp3",NULL);
    bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
    gst_bus_add_watch(bus,bus_call,loop);       //添加消息监视器
    gst_object_unref(bus);
    gst_bin_add_many(GST_BIN(pipeline),source,decoder,sink,NULL);
    gst_element_link_many(source,decoder,sink,NULL);
    gst_element_set_state(pipeline,GST_STATE_PLAYING);
    g_main_loop_run(loop);
    gst_element_set_state(pipeline,GST_STATE_NULL);
    gst_object_unref(GST_OBJECT(pipeline));
}
